﻿using GWB.Application.Dto;
using GWB.SqlSugar;
using GWB.SqlSugar.Model;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Org.BouncyCastle.Utilities.Zlib;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Runtime.Intrinsics.X86;
using System.Text;
using System.Threading.Tasks;

namespace GWB.Application
{
    public class LogService : Repository<VisitorLog>, ILogService
    {
      //private IHttpContextAccessor Accessor{ get; set; }

      //private LogService(IHttpContextAccessor context)
      //{
      //    Accessor= context;
      //}

        public VisitorLogInfoOutDto GetVisitorLogInfo()
        {
           
            //var v1 = Accessor.HttpContext.Request.Headers["SERVER_NAME"];       // '获取服务器IP
            //var v2 = Accessor.HttpContext.Request.Headers["HTTP_REFERER"];       //       '获取访问来源页面
            //var v3 = Accessor.HttpContext.Request.Headers["OS"];       //                              '获取操作系统
            //var v4 = Accessor.HttpContext.Request.Headers["APPL_PHYSICAL_PATH"];       //     '获取IIS物理路径
            //var v5 = Accessor.HttpContext.Request.Headers["SCRIPT_NAME"];       //                  '获取虚拟路径
            //var v6 = Accessor.HttpContext.Request.Headers["NUMBER_OF_PROCESSORS"];       //    '获取服务器CPU个数
            //var v7 = Accessor.HttpContext.Request.Headers["SERVER_PORT"];       //                '服务器处理请求的端口
            //var v8 = Accessor.HttpContext.Request.Headers["Url"];       //                           返回服务器地址
            //var v9 = Accessor.HttpContext.Request.Headers["Path_Info"];       //                 客户端提供的路径信息
            //var v10 = Accessor.HttpContext.Request.Headers["Appl_Physical_Path"];       // 与应用程序元数据库路径相应的物理路径
            //var v11 = Accessor.HttpContext.Request.Headers["Path_Translated"];       //      通过由虚拟至物理的映射后得到的路径
            //var v12= Accessor.HttpContext.Request.Headers["Script_Name"];       //           执行脚本的名称
            //var v13= Accessor.HttpContext.Request.Headers["Query_String"];       //          查询字符串内容
            //var v14= Accessor.HttpContext.Request.Headers["Http_Referer"];       //          请求的字符串内容
            //var v15= Accessor.HttpContext.Request.Headers["Server_Port"];       //             接受请求的服务器端口号
            //var v16= Accessor.HttpContext.Request.Headers["Remote_Addr"];       //        发出请求的远程主机的IP地址
            //var v17= Accessor.HttpContext.Request.Headers["Remote_Host"];       //        发出请求的远程主机名称
            //var v18= Accessor.HttpContext.Request.Headers["Local_Addr"];       //            返回接受请求的服务器地址
            //var v19= Accessor.HttpContext.Request.Headers["Http_Host"];       //             返回服务器地址
            //var v20= Accessor.HttpContext.Request.Headers["Server_Name"];       //        服务器的主机名、DNS地址或IP地址
            //var v21= Accessor.HttpContext.Request.Headers["Request_Method"];       // 提出请求的方法比如GET、HEAD、POST等等
            //var v22= Accessor.HttpContext.Request.Headers["Server_Port_Secure"];       //    如果接受请求的服务器端口为安全端口时，则为1，否则为0
            //var v23= Accessor.HttpContext.Request.Headers["Server_Protocol"];       //       服务器使用的协议的名称和版本
            //var v24= Accessor.HttpContext.Request.Headers["Server_Software"];       //    应答请求并运行网关的服务器软件的名称和版本
            //var v25= Accessor.HttpContext.Request.Headers["All_Http"];       //    客户端发送的所有HTTP标头，前缀HTTP_
            //var v26= Accessor.HttpContext.Request.Headers["All_Raw"];       //    客户端发送的所有HTTP标头,其结果和客户端发送时一样，没有前缀HTTP_
            //var v27= Accessor.HttpContext.Request.Headers["Appl_MD_Path"];       //    应用程序的元数据库路径
            //var v28= Accessor.HttpContext.Request.Headers["Content_Length"];       //     客户端发出内容的长度
            //var v29= Accessor.HttpContext.Request.Headers["Https"];       //   如果请求穿过安全通道（SSL），则返回ON如果请求来自非安全通道，则返回OFF
            //var v30= Accessor.HttpContext.Request.Headers["Instance_ID"];       //      IIS实例的ID号
            //var v31= Accessor.HttpContext.Request.Headers["Instance_Meta_Path"];       //      响应请求的IIS实例的元数据库路径
            //var v32= Accessor.HttpContext.Request.Headers["Http_Accept_Encoding"];       //   返回内容如：gzip,deflate
            //var v33= Accessor.HttpContext.Request.Headers["Http_Accept_Language"];       //  返回内容如：en - us
            //var v34= Accessor.HttpContext.Request.Headers["Http_Connection"];       //   返回内容：Keep - Alive
            //var v35= Accessor.HttpContext.Request.Headers["Http_Cookie"];       //     返回内容：Cookie的值
            //var v36= Accessor.HttpContext.Request.Headers["Http_User_Agent"];       //     返回内容：Mozilla / 4.0[compatible; MSIE6.0; WindowsNT5.1; SV1]
            //var v37= Accessor.HttpContext.Request.Headers["Https_Keysize"];       //               安全套接字层连接关键字的位数，如128
            //var v38= Accessor.HttpContext.Request.Headers["Https_Secretkeysize"];       //      服务器验证私人关键字的位数如1024
            //var v39 = Accessor.HttpContext.Request.Headers["Https_Server_Issuer"];       //      服务器证书的发行者字段
            //var v40 = Accessor.HttpContext.Request.Headers["Https_Server_Subject"];       //    服务器证书的主题字段
            //var v41= Accessor.HttpContext.Request.Headers["Auth_Password"];       //              当使用基本验证模式时，客户在密码对话框中输入的密码
            //var v42= Accessor.HttpContext.Request.Headers["Auth_Type"];       //                     是用户访问受保护的脚本时，服务器用於检验用户的验证方法
            //var v43= Accessor.HttpContext.Request.Headers["Auth_User"];       //                代证的用户名
            //var v44 = Accessor.HttpContext.Request.Headers["Cert_Cookie"];       //              唯一的客户证书ID号
            //var v45= Accessor.HttpContext.Request.Headers["Cert_Flag"];       //         客户证书标志，如有客户端证书，则bit0为0如果客户端证书验证无效，bit1被设置为1
            //var v46= Accessor.HttpContext.Request.Headers["Cert_Issuer"];       //                 用户证书中的发行者字段
            //var v47= Accessor.HttpContext.Request.Headers["Cert_Keysize"];       //                安全套接字层连接关键字的位数，如128
            //var v48= Accessor.HttpContext.Request.Headers["Cert_Secretkeysize"];       //      服务器验证私人关键字的位数如1024
            //var v49= Accessor.HttpContext.Request.Headers["Cert_Serialnumber"];       //     客户证书的序列号字段
            //var v50= Accessor.HttpContext.Request.Headers["Cert_Server_Issuer"];       //      服务器证书的发行者字段
            //var v51= Accessor.HttpContext.Request.Headers["Cert_Server_Subject"];       //    服务器证书的主题字段
            //var v52= Accessor.HttpContext.Request.Headers["Cert_Subject"];       //                客户端证书的主题字段
            //var v53= Accessor.HttpContext.Request.Headers["Content_Type"];       //              客户发送的form内容或HTTPPUT的数据类型

           

            return new VisitorLogInfoOutDto()
            {
                //v1=@"v1:"+v1+"____"+
                //   "v2:" + v2 + "____"+
                //   "v3:" + v3 + "____" +
                //   "v4:" + v4 + "____" +
                //   "v5:" + v6 + "____" +
                //   "v6:" + v6 + "____" +
                //   "v7:" + v7 + "____" +
                //   "v8:" + v8 + "____" +
                //   "v9:" + v9 + "____" +
                //   "v10:" + v10 + "____" +
                //   "v11:" + v11 + "____" +
                //   "v12:" + v12 + "____" +
                //   "v13:" + v13 + "____" +
                //   "v14:" + v14 + "____" +
                //   "v15:" + v15 + "____" +
                //   "v16:" + v16 + "____" +
                //   "v17:" + v17 + "____" +
                //   "v18:" + v18 + "____" +
                //   "v19:" + v19 + "____" +
                //   "v20:" + v20 + "____" +
                //   "v21:" + v21 + "____" +
                //   "v22:" + v22 + "____" +
                //   "v23:" + v23 + "____" +
                //   "v24:" + v24 + "____" +
                //   "v25:" + v25 + "____" +
                //   "v26:" + v26 + "____" +
                //   "v27:" + v27 + "____" +
                //   "v28:" + v28 + "____" +
                //   "v29:" + v29 + "____" +
                //   "v30:" + v30 + "____" +
                //   "v31:" + v31 + "____" +
                //   "v32:" + v32 + "____" +
                //   "v33:" + v33 + "____" +
                //   "v34:" + v34 + "____" +
                //   "v35:" + v35 + "____" +
                //   "v36:" + v36 + "____" +
                //   "v37:" + v37 + "____" +
                //   "v38:" + v38 + "____" +
                //   "v39:" + v39 + "____" +
                //   "v40:" + v40 + "____" +
                //   "v41:" + v41 + "____" +
                //   "v42:" + v42 + "____" +
                //   "v43:" + v43 + "____" +
                //   "v44:" + v44 + "____" +
                //   "v45:" + v45 + "____" +
                //   "v46:" + v46 + "____" +
                //   "v47:" + v47 + "____" +
                //   "v48:" + v48 + "____" +
                //   "v49:" + v49 + "____" +
                //   "v50:" + v50 + "____" +
                //   "v51:" + v51 + "____" +
                //   "v52:" + v52 + "____" +
                //   "v53:" + v53 + "____" ,
               // v2 = JsonConvert.SerializeObject(Accessor.HttpContext.Request.Headers),
            };
           //var visitorTotal=base.Context.Queryable<VisitorLog>() 
           // .GroupBy(it => it.CreateTime)
           // .Select(it => new { Count = SqlFunc.AggregateCount(it.CreateTime), CreateTime = it.CreateTime })
           // .Count();

            var visitorTotalPeople = base.Context.Queryable<VisitorLog>()
            .GroupBy(it => it.IP)
            .Select(it => new { Count = SqlFunc.AggregateCount(it.IP), CreateTime = it.IP })
            .Count();


            var visitorTotal = base.Context.Queryable<VisitorLog>()
                .Select(it => new
                {
                    year = it.CreateTime.Year,
                    month = it.CreateTime.Month,
                    day = it.CreateTime.Day,
                    hour = it.CreateTime.Hour,
                    minute = it.CreateTime.Minute
                })
                .MergeTable()
                .GroupBy(it => new { it.year, it.month,it.day,it.minute,it.hour })
                .Select(it => new
                {
                    date = SqlFunc.MergeString(it.year.ToString(), "-", it.month.ToString()),
                }).Count();



            var VisitorTotalPeople = base.Context.Queryable<VisitorLog>().GroupBy(x => x.Id).Count();

            return new VisitorLogInfoOutDto()
            {

                VisitorTotal= visitorTotal,
                VisitorTotalPeople= visitorTotalPeople
            };
        }

        public override int InsertReturnIdentity(VisitorLog insertObj)
        {
            return 0;
            var maxLog = base.Context.Queryable<VisitorLog>().Where(x => x.Route == insertObj.Route&&x.IP== insertObj.IP).Max(x => x.CreateTime);

            if (maxLog==null||DateTime.Now.AddMinutes(-5)> maxLog)
            {
                return base.InsertReturnIdentity(insertObj);
            }
            else
            {
                return 0;
            }
          
        }

        public string Send(string msg)
        {
            var res = "";

            var url = "https://api.openai.com/v1/completions";
            var data = "{ \"model\": \"text-davinci-003\", \"prompt\": \""+msg+"\", \"temperature\": 0, \"max_tokens\": 2048 }";
            var headers=new Dictionary<string, string>();
            headers.Add("Authorization", "Bearer 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");

            try
            {
                var result = HttpWebRequest(url, data, Encoding.UTF8, headers);
               var resData= JsonConvert.DeserializeObject<ResEntity>(result);
               foreach (var item in resData.choices)
               {
                   res += item.text;
               }
               return res;
            }
            catch (Exception e)
            {
                return "系统错误:"+e.ToString();
            }
        }

        public static string HttpWebRequest(string url, string data, Encoding encoding,  Dictionary<string, string>? headers = null, int timeout = 100000, string contentType = "application/json")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            //  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);

            //请求方式
            request.Method ="post";
            //请求过期时间
            request.Timeout = timeout;
            //内容类型
            request.ContentType = contentType;
            //添加请求头
            if (headers != null)
            {
                foreach (var (key, value) in headers)
                {
                    request.Headers.Add(key, value);
                }
            }
            var result = string.Empty;

            byte[] byteArray = encoding.GetBytes(data);
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            dataStream = response.GetResponseStream();
            using (StreamReader myStreamReader = new StreamReader(dataStream, encoding))
            {
                result = myStreamReader.ReadToEnd();
                myStreamReader.Close();
            }
            response.Close();
            dataStream.Close();


            return result;
        }

        public class ResEntity
        {
            public string id { get; set; }

            public string obj   { get; set; }

            public int created { get; set; }

            public string model { get; set; }

            public List<ChoicesItem> choices { get; set; }

            public Usage usage { get; set; }
        }
        public class Usage
        {
            public int prompt_tokens { get; set; }

            public int completion_tokens { get; set; }

            public int total_tokens { get; set; }
        }
        public class ChoicesItem
        {
            public string text { get; set; }

            public int index { get; set; }

            public string logprobs { get; set; }

            public string finish_reason { get; set; }
        }
}
}
